import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NavController, NavParams, ToastController, Nav } from 'ionic-angular';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { SignupPage } from '../signup/signup';
import { PasswordPage } from '../password/password';
import { TabsPage } from '../tabs/tabs';
import { ScanPage } from '../scan/scan';
import { Base64 } from 'js-base64';

import * as _ from 'lodash';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  group: FormGroup;
  InstitutionId = 1;
  InstitutionPrefix = null;

  personName = null;
  constructor(public navCtrl: NavController,
    public nav: Nav,
    public navParams: NavParams,
    public translate: TranslateService,
    private rest: RestService,
    private toastCtrl: ToastController,
    private builder: FormBuilder,
    private restService: RestService) {
    this.group = this.builder.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required]]
    });
  }

  clearUsername() {
    this.group.controls.username.setValue('');
  }

  signup() {
    this.navCtrl.push(SignupPage, {});
  }

  forgetPassword() {
    this.navCtrl.push(PasswordPage, {});
  }

  login() {
    const username = this.group.controls.username.value;
    const password = this.group.controls.password.value;

    this.restService.clearup();
    this.restService.getTokenFromServer({
      grant_type: 'password',
      username: username,
      password: password,
      client_id: 'webmobile',
    }, (data) => {


      const token = data['access_token'];
      const refreshToken = data['refresh_token'];
      const userInfo = JSON.parse(Base64.decode(token.split('.')[1]));
      const user = {
        username: username,
        password: password,
        locale: userInfo.locale,
        role: ''
      };

      const roles = userInfo.realm_access.roles;
      if (_.isEmpty(roles)) {
        console.error('user have not assigned any roles');
        this.showToast(this.translate.get('invalidUserRole')['value']);
        return;
      }

      const validRoles = this.restService.listValidRoles();
      roles.forEach(role => {
        if (validRoles.indexOf(role) !== -1) {
          user.role = role;
        }
      });

      if (!user.role) {
        this.showToast(this.translate.get('invalidUserRole')['value']);
        return;
      }

      this.restService.saveToken(token);
      this.restService.saveRefreshToken(refreshToken);
      this.restService.saveUser(user);
      this.restService.startRefreshToken();

// if (localStorage.getItem('personName') != username ||
// localStorage.getItem('InstitutionPrefix') != this.InstitutionPrefix) {
//   localStorage.clear();
//   localStorage.setItem('InstitutionPrefix',this.InstitutionPrefix);
// }


if (this.InstitutionPrefix != null && this.InstitutionPrefix !=""){
  // this.rest.clearup();

  this.restService.getWithParams('/data/institution/search/ip', {
    ip: this.InstitutionPrefix
      }).subscribe(resp => {
        if (resp['_embedded']['institutions'].length > 0){
          this.InstitutionId = resp['_embedded']['institutions'][0]['id'];
          this.rest.institutionId = this.InstitutionId;
          this.navAftLogin (username);
        } else {
          this.nav.setRoot(LoginPage);
          this.showToast(this.translate.get('pleaseInputInstituteId')['value']);
        }
      }, message => {
        // this.rest.institutionId = 1;
        this.showToast(this.translate.get('pleaseInputInstituteId')['value']);
      });
    } else {
      this.rest.institutionId = 1;
      this.navAftLogin (username);
    }

    }, () => {
      this.restService.get('/api/keycloak/validate/' + username).subscribe(data => {
        if (data.status === 404) {
          this.showToast(this.translate.get('userNotFound')['value']);
        } else {
          this.showToast(this.translate.get('wrongPassword')['value']);
        }
      }, message => {
        this.showToast(this.translate.get('failedToken')['value']);
        console.error(JSON.stringify(message));
      });
    });
  }

  navAftLogin (username) {
          // this.personName = "13000000001";
          this.personName = localStorage.getItem('personName');
          if (this.personName && this.personName == username && this.InstitutionId == 1) {
            this.nav.setRoot(TabsPage, { personName: this.personName });
          } else if (this.personName && this.personName != username && this.InstitutionId == 1) {
            localStorage.removeItem('devices');
            localStorage.setItem('personName', username);
            this.nav.setRoot(TabsPage, { personName: username });
          } else {
            localStorage.setItem('personName', username);
            if (this.InstitutionId == 1) {
              this.rest.viewOnly = false;
            } else {
              this.rest.viewOnly = true;
            }
            localStorage.setItem('viewOnly', JSON.stringify(this.rest.viewOnly));
            if (this.rest.developing == true) {
              this.nav.setRoot(ScanPage, { personName: "13000000001" });  //For debuging purpose
            } else {
              this.nav.setRoot(ScanPage, { personName: username });
            }
          }

  }
  showToast(message) {
    const toast = this.toastCtrl.create({
      message: message,
      duration: 5000,
      position: 'bottom'
    });

    toast.present(toast);
  }

  ionViewDidEnter() {
    const user = this.restService.getUser();
    if (_.isEmpty(user)) {
      return;
    }

    if (user.username) {
      this.group.controls.username.setValue(user.username);
    }
  }
}
